/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package trabajo.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Max
 */
public class Archivo {

    private String ruta;
    private File arch;
    
    public Archivo(String ruta) {
        this.ruta = ruta;
        iniciar();
    }
    
    private void iniciar() {
        arch = new File(ruta);
        if (!arch.exists()) {
            try {
                arch.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public ArrayList<String> leer() {
        ArrayList<String> lista = new ArrayList<String>();
        FileReader fr = null;
        try {
            fr = new FileReader(arch);
            BufferedReader br = new BufferedReader(fr);
            String tem;
            while (true) {
                try {
                    tem = br.readLine();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "No existen datos" + e.getMessage());
                    return lista;
                }
                if (tem == null) {
                    break;
                }
                lista.add(tem);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fr.close();
            } catch (IOException ex) {
                Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return lista;
    }

    public void escribir(String contenido) throws Exception{
        ArrayList<String> content = leer();
        content.add(contenido);
        
        FileWriter fw = new FileWriter(arch);
        PrintWriter pw = new PrintWriter(fw);
        String txt;
        for (int i = 0; i < content.size(); i++) {            
            pw.println(content.get(i));
        }
        pw.close();
        fw.close();
    }
    
}
